<template>
  <view class="sku-item">
    <view class="sku-container">
      <view v-if="showSkuList && skuList.length" class="cartSkuList">
        <view v-for="(skuAry, key) in skuItemList" :key="key" class="cartSkuItem">
          <view class="skuTitl">{{ key }}</view>
          <view class="skuList">
            <view
              v-for="(element, index) in skuAry"
              :key="index"
              class="skuItem"
              :class="{'selected': element.checked, 'unEnable': !element.enable}"
              @click="selectSkuItem(element, key)">{{ element.name }}</view>
          </view>
        </view>
      </view>
      <view v-else-if="comboList.length && showCombo" class="cartSkuList">
        <view class="cartSkuItem">
          <view class="skuList">
            <view
              v-for="(item, index) in comArr"
              :key="index"
              class="skuItem combo"
              :class="{'selected': item.checked, 'unEnable': !item.enable}"
              @click="selectComboItem(item, index)">
              <image class="img" :src="item.pic"></image>{{ item.title }}</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'SkuItem',
  props: {
    skuOrigin: {
      type: Object,
      default() {
        return {}
      }
    },
    skuList: {
      type: Array,
      default() {
        return []
      },
      require: true
    },
    comboList: {
      type: Array,
      default() {
        return []
      },
      require: false
    },
    goodsType: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      comboListArr: [],
      skuItemList: {},
      unEnableList: [],
      comArr: [],
      selectKey: [],
      showCombo: false,
      showSkuList: true
    }
  },
  computed: {
    selectedSkuItem() {
      const selectKeyText = this.selectKey.join(';')
      let selected = null
      if (!this.skuList.length) {
        return selected
      }
      this.skuList.forEach(item => {
        if (item.properties_name === selectKeyText) {
          selected = item
        }
      })
      return selected
    }
  },
  async created() {
    await this.init()
    this.comboListArr = this.comboList
  },
  methods: {
    async init() {
      if (this.comboList.length) {
        const arr = []
        this.comboList.map(element => {
          element.checked = false
          arr.push(element)
        })
        this.comArr = arr
        this.showCombo = true
        return
      }
      this._formatSkuList(this.skuList)
      if (this.skuList.length === 1) {
        for (const x in this.skuItemList) {
          this.selectSkuItem(this.skuItemList[x][0], x)
        }
        if (this.goodsType === 2) {
          this.showSkuList = false
        }
      } else if (this.skuOrigin && this.skuOrigin.selectedSkuItem) {
        const temp1 = this.skuOrigin.selectedSkuItem.properties_name.split(';')
        temp1.forEach(item => {
          const temp2 = item.split(':')
          let selSku = null
          for (const x in this.skuItemList) {
            this.skuItemList[x].forEach(sSku => {
              if (sSku.name === temp2[1]) {
                selSku = sSku
              }
            })
          }
          this.selectSkuItem(selSku, temp2[0])
        })
      } else {
        this.$emit('selectedItem', null)
      }
    },
    _formatSkuList(data) {
      if (!data.length) {
        return
      }
      // sku序列化 skuItemList 将获取到的字符串序列化成key : []
      const tempSkuItemList = {}
      data.forEach(element => {
        // 颜色:正红;尺码:XXS
        const temp1 = element.properties_name.split(';')
        if (element.num < 1) {
          this.unEnableList.push(temp1)
        }
        temp1.forEach(item => {
          const temp2 = item.split(':')
          if (!tempSkuItemList[temp2[0]]) {
            tempSkuItemList[temp2[0]] = []
          }
          const skuItem = {
            name: temp2[1],
            checked: false,
            enable: true
          }
          let isHasVal = false
          for (let index = 0; index < tempSkuItemList[temp2[0]].length; index++) {
            if (tempSkuItemList[temp2[0]][index].name === skuItem.name) {
              isHasVal = true
            }
          }
          if (!isHasVal) {
            tempSkuItemList[temp2[0]].push(skuItem)
          }
        })
      })
      /* 列出所有选项的排列组合,把不存在的商品添加到不可用列表中 */
      const exchangeAry = []
      for (const x in tempSkuItemList) {
        const tempEchange = tempSkuItemList[x].map(item => {
          return x + ':' + item.name
        })
        exchangeAry.push(tempEchange)
      }
      const newArr = this.doExchange(exchangeAry, 0, [], [])
      newArr.forEach(item => {
        let ishaveVal = false
        data.forEach(element => {
          if (element.properties_name === item) {
            ishaveVal = true
          }
        })
        if (!ishaveVal) {
          this.unEnableList.push(item.split(';'))
        }
      })
      /* 列出所有选项的排列组合,把不存在的商品添加到不可用列表中 end */
      this.skuItemList = tempSkuItemList
      this.checkSkuEnable()
      // this.unEnableList = ['颜色:正红;尺码:XXS'.split(';')]
    },
    selectSkuItem(item, key) {
      if (!item.enable) {
        return
      }
      this.skuItemList[key].forEach(element => {
        if (item.name !== element.name) {
          element.checked = false
        }
      })
      item.checked = !item.checked
      this.checkSkuEnable()
      if (this.selectedSkuItem) {
        this.selectedSkuItem.selectText = this.selectText
      }
      this.$emit('selectedItem', this.selectedSkuItem)
    },
    checkSkuEnable() {
      /* 检验sku是否可用 */
      const selectKey = []
      const selectTextAry = []
      const currTimes = {}
      this.selectText = ''
      // 确认每个不可用sku出现的次数以及其最多出现次数
      for (const x in this.skuItemList) {
        currTimes[x] = {}
        currTimes[x].limit = 999
        let tempLim = 1
        for (const y in this.skuItemList) {
          if (x !== y) {
            tempLim *= this.skuItemList[y].length
            // currTimes[x].limit = Math.min(this.skuItemList[y].length, currTimes[x].limit)
          }
        }
        currTimes[x].limit = tempLim

        this.skuItemList[x].forEach(item => {
          item.enable = true
          if (item.checked) {
            selectKey.push(`${x}:${item.name}`)
            selectTextAry.push(item.name)
          }
        })
      }
      // 给出当前被选中的sku文字
      this.selectText = selectTextAry.join('; ')
      this.unEnableList.forEach(unItem => {
        unItem.forEach(cur => {
          const unStrKty = cur.split(':')
          if (!currTimes[unStrKty[0]][unStrKty[1]]) {
            currTimes[unStrKty[0]][unStrKty[1]] = {}
            currTimes[unStrKty[0]][unStrKty[1]].times = 1
          } else {
            currTimes[unStrKty[0]][unStrKty[1]].times++
          }
        })

        const uniTemp = unItem.filter(sub => {
          return !selectKey.some(ele => ele === sub)
        })
        if (uniTemp.length === 1) {
          const disArr = uniTemp[0].split(':')
          this.skuItemList[disArr[0]].forEach(sk => {
            if (disArr[1] === sk.name) {
              sk.enable = false
            }
          })
        }
      })
      for (const x in currTimes) {
        for (const y in currTimes[x]) {
          if (currTimes[x][y].times) {
            if (currTimes[x][y].times >= currTimes[x].limit) {
              this.skuItemList[x].forEach(sk => {
                if (y === sk.name) {
                  sk.enable = false
                }
              })
            }
          }
        }
      }
      this.selectKey = selectKey
    },
    doExchange(arr, depth, result, results) {
      for (var i = 0; i < arr[depth].length; i++) {
        result[depth] = arr[depth][i]
        if (depth !== arr.length - 1) {
          this.doExchange(arr, depth + 1, result, results)
        } else {
          results.push(result.join(';'))
        }
      }
      return results
    },
    // 选择组合套餐商品
    selectComboItem(item, key) {
      if (!item.enable || item.checked) {
        return
      }
      this.comboListArr.map((element, index) => {
        if (item.goods_id !== element.goods_id) {
          element.checked = false
        }
        return element
      })
      item.checked = !item.checked
      item.selectText = item.title
      item.order_limit = item.goods_pack.limit_num
      item.min_num = item.goods_pack.min_num
      item.goods_pic = item.pic
      this.$forceUpdate(this.comboList)
      this.$emit('selectedItem', item)
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .sku-item {
    overflow: hidden;
    min-height: 100rpx;
    .cartSkuList {
      .cartSkuItem {
        .skuTitl {
          color: $color-title;
          margin-bottom: 20rpx;
        }
        .skuList {
          display: flex;
          flex-wrap: wrap;
          .skuItem {
            // flex: 0 0 calc(33.33% - 16rpx);
            flex: 0 0 222rpx;
            overflow: hidden;
            // margin-right: 20rpx;
            margin-right:20rpx;
            box-sizing: border-box;
            margin-bottom: 20rpx;
            // border-radius: 30rpx;
            height: 60rpx;
            text-align: center;
            line-height: 60rpx;
            border: 2rpx solid #666;
            &:nth-of-type(3n) {
              margin-right: 0;
            }
            &.combo {
              display: flex;
              flex: inherit;
              line-height: 35rpx;
              text-align: left;
              height: auto;
              padding: 10rpx 15rpx;
              border-radius: 20rpx;
              .img {
                width: 45rpx;
                height: 45rpx;
                margin-right: 10rpx;
              }
            }
          }
          .selected{
            // background-color: $color-theme;
            // border: 2rpx solid $color-theme;
            background-color: #000;
            border: 2rpx solid #000;
            color: white;
          }
          .unEnable{
            color: #ccc;
            background-color: #EAEAEA;
            border: 2rpx solid #EAEAEA;
          }
        }
      }
    }
  }
</style>
